package com.datas.service.baseentity;

import com.datas.beans.DatatablesPager;
import com.datas.db.hibernatebeans.UmsRole;
import com.datas.service.GuanlianService;
import com.datas.utils.hbn.HbnTxRuner;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by jige0727 on 2017/5/28.
 */
@Service
public class RolesService {
    @Autowired
    GuanlianService guanlianService;

    public Integer create(UmsRole role) {
        Integer res = (Integer) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                return create(role, getCurrentSession());
            }
        }.runTx();
        return res;
    }

    public Integer create(UmsRole role, Session session) {
        if (!isExistRole(role.getRole_code(), session)) {
            session.save(role);
            return 1;
        }
        return 0;
    }

    /**
     * 判断重复
     *
     * @param roleCode
     * @param session
     * @return
     */
    private Boolean isExistRole(String roleCode, Session session) {
        String hql = "select count(*) " +
                "from UmsRole i " +
                "where i.role_code=:roleCode ";
        Long count = (Long) session.createQuery(hql)
                .setParameter("roleCode", roleCode).uniqueResult();
        return count != null && count > 0;
    }

    public Integer modify(UmsRole role) {
        Integer res = (Integer) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                return modify(role, getCurrentSession());
            }
        }.runTx();
        return res;
    }

    private Integer modify(UmsRole role, Session session) {
        UmsRole dataInDb = session.get(UmsRole.class, role.getId());
        role.setCreate_date(dataInDb.getCreate_date());
        role.setModify_date(new Date());
        session.evict(dataInDb);

        session.update(role);
        return 1;
    }

    /**
     * 返回 1成功 0失败，有子节点
     *
     * @param id
     * @return
     */
    public Integer delete(Integer id) {
        Integer res = (Integer) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                UmsRole data = getCurrentSession().get(UmsRole.class, id);
                guanlianService.delGl_all_role(id, getCurrentSession());
                getCurrentSession().delete(data);
                return 1;
            }
        }.runTx();
        return res;
    }

    public UmsRole info(Integer id) {
        UmsRole data = (UmsRole) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                return getCurrentSession().get(UmsRole.class, id);
            }
        }.run();
        return data;
    }

    /////////////////////////////////////////
    public void list(DatatablesPager pager) {
        Integer res = (Integer) new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                List<UmsRole> data = list(pager, getCurrentSession());
                pager.setData(data);
                pager.setRecordsFiltered(list_filtered(pager, getCurrentSession()));
                pager.setRecordsTotal(list_total(getCurrentSession()));
                return 1;
            }
        }.run();
    }

    private List<UmsRole> list(DatatablesPager pager, Session session) {
        String searchValue = pager.getSearchValue();
        String hql = "from UmsRole i " +
                "where i.disabled =0 " +
                "and (i.role_name like :searchValue " +
                "or i.role_code like :searchValue) ";
        Query query = session.createQuery(hql);
        List<UmsRole> data = query
                .setParameter("searchValue", searchValue)
                .setFirstResult(pager.getStart())
                .setMaxResults(pager.getLength())
                .list();
        return data;
    }

    private Long list_filtered(DatatablesPager pager, Session session) {
        String searchValue = pager.getSearchValue();
        String hql = "select count(*) from UmsRole i " +
                "where i.disabled =0 " +
                "and (i.role_name like :searchValue " +
                "or i.role_code like :searchValue) ";
        Query query = session.createQuery(hql);
        Long count = (Long) query
                .setParameter("searchValue", searchValue)
                .uniqueResult();
        return count;
    }

    private Long list_total(Session session) {
        String hql = "select count(*) from UmsRole i " +
                "where i.disabled =0 ";
        Long count = (Long) session.createQuery(hql)
                .uniqueResult();
        return count;
    }

    public JSONArray listWithRoleGL(Integer userid) {
        Set<Integer> ids = new HashSet<>();
        new HbnTxRuner() {
            @Override
            protected Object dataLogic() throws Exception {
                List<Integer> datas = getCurrentSession()
                        .createQuery("select i.roles_id " +
                                "from UmsUser_UmsRole i where i.users_id=:userid ")
                        .setParameter("userid", userid).list();
                ids.addAll(datas);
                return 1;
            }
        }.run();
        return new JSONArray(ids);
    }
}
